const express = require("express");
const upload = require("./upload");
const jwt = require("jsonwebtoken");
const mysql = require("mysql2/promise");
const pool = require("./db");

const app = express();
app.use(express.json()); // 用于解析 JSON 请求体

const SECRET_KEY = "jwtKey881"; // jwt 密钥
const PORT = process.env.PORT || 3000; //端口

// 创建 uploads 目录
const fs = require("fs");
const path = require("path");
if (!fs.existsSync(path.join(__dirname, "uploads"))) {
  fs.mkdirSync("uploads");
}

// 认证 JWT 的中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  console.log("token", token);
  if (token == null)
    return res.status(401).json({ code: 401, data: null, msg: "未授权" });

  jwt.verify(token, SECRET_KEY, (err, user) => {
    console.log("错误", err);
    if (err)
      return res
        .status(403)
        .json({ code: 403, msg: "token过期，请重新登录", data: null });

    req.user = user;
    next();
  });
}

/**生成token */
function generateToken(user) {
  const token = jwt.sign(
    { userId: user.id, username: user.username },
    SECRET_KEY,
    { expiresIn: "1h" }
  );
  return token;
}

/**解析 JWT */
function analysisToken(token, privateKey) {
  try {
    const decoded = jwt.verify(token, privateKey);
    console.log("Decoded JWT:", decoded);
    return decoded;
  } catch (err) {
    console.error("Failed to decode JWT:", err.message);
  }
}

//模块划分接口

/*****************************首页*/

/**新增作品 */
app.post(
  "/api/saveItem",
  authenticateToken,
  upload.single("img"),
  async (req, res) => {
    try {
      const { title, content } = req.body;
      const authHeader = req.headers["authorization"];
      const token = authHeader && authHeader.split(" ")[1];
      const jwtInfo = analysisToken(token, SECRET_KEY);
      console.log("JWT解析", jwtInfo);
      if (!req.file) {
        return res.status(400).send({ message: "请上传图片" });
      }
      const [rows] = await pool.query(
        `INSERT INTO home (title, content,cover_plan) VALUES (?, ?, ?)`,
        [title, content, req.file.filename]
      );
      if (rows.affectedRows == 1) {
        res
          .status(200)
          .json({ code: 200, data: rows.insertId, msg: "操作成功" });
      } else {
        res.status(201).json({ code: 201, data: null, msg: "保存出错了" });
      }
    } catch (err) {
      res
        .status(500)
        .json({ code: 500, data: null, msg: "服务器出错了:" + err });
    }
  }
);

/**新增作品上传的图片 */
app.post(
  "/api/saveItem/updateImg",
  authenticateToken,
  upload.single("img"),
  async (req, res) => {
    try {
      const { itemId } = req.body;
      const [rows] = await pool.query(
        `INSERT INTO home_detail (img, home_id) VALUES (?, ?)`,
        [req.file.fieldname, itemId]
      );
      if (rows.affectedRows == 1) {
        res
          .status(200)
          .json({ code: 200, data: rows.insertId, msg: "操作成功" });
      } else {
        res
          .status(201)
          .json({ code: 201, data: rows.insertId, msg: "保存图片出错了" });
      }
    } catch (err) {
        res
        .status(500)
        .json({ code: 500, data: null, msg: "服务器出错了:" + err });
    }
  }
);

/**获取首页分页信息（标题-图片） */

app.get("/api/productionList", authenticateToken, async (req, res) => {
    try {
        const { page, pageSize }=req.query;
      const [rows] = await pool.query("SELECT * FROM invite WHERE id=1");
      res.status(200).json({ code: 200, data: rows, msg: null });
    } catch (err) {
      res
        .status(500)
        .json({ code: 500, data: null, msg: "Error fetching invite" });
    }
  });

/******************************导航信息接口 */

/**修改导航信息（admin） */

// 获取导航信息
app.get("/api/getInviteInfo", authenticateToken, async (req, res) => {
  try {
    const [rows] = await pool.query("SELECT * FROM invite WHERE id=1");
    res.status(200).json({ code: 200, data: rows, msg: null });
  } catch (err) {
    res
      .status(500)
      .json({ code: 500, data: null, msg: "Error fetching invite" });
  }
});

/*******************************我的 */
//修改头像
app.post(
  "/api/upload-avatar",
  authenticateToken,
  upload.single("avatar"),
  async (req, res) => {
    try {
      const authHeader = req.headers["authorization"];
      const token = authHeader && authHeader.split(" ")[1];
      const jwtInfo = analysisToken(token, SECRET_KEY);
      console.log("JWT解析", jwtInfo);
      if (!req.file) {
        return res.status(400).send({ message: "请上传图片" });
      }
      //删除本地图片文件
      const [[imgId]] = await pool.query(
        "SELECT u.avatar FROM users u WHERE id=?",
        [jwtInfo.userId]
      );
      console.log("图片文件名称", imgId.avatar);
      const imgUrl = `./uploads/${imgId.avatar}`;
      fs.unlink(imgUrl, (err) => {
        if (err) {
          console.error("Error occurred while deleting the file:", err);
        }
      });
      console.log("文件", req.file);
      await pool.query("UPDATE users SET avatar= ? WHERE id=?", [
        req.file.filename,
        jwtInfo.userId,
      ]);
      // 文件 URL 生成（可以根据自己的逻辑生成）
      const fileUrl = `http://localhost:${PORT}/uploads/${req.file.filename}`;
      console.log("url", fileUrl);
      res.status(200).json({ code: 200, data: null, msg: "操作成功" });
    } catch (err) {
      res
        .status(500)
        .json({ code: 500, data: null, msg: "服务器出错了:" + err });
    }
  }
);

//登录
app.post("/api/login", async (req, res) => {
  const { username, password } = req.body;
  console.log("用户", req, res);
  try {
    const [rows] = await pool.query(
      "SELECT * FROM users WHERE username = ? AND password = ?",
      [username, password]
    );
    console.log("用户", rows);
    if (rows.length > 0) {
      const user = rows[0];
      // 生成 token
      const token = generateToken(user);

      res.status(200).json({
        code: 200,
        data: { userInfo: rows, token: token },
        msg: "登录成功",
      });
    } else {
      res.status(201).json({ code: 201, data: null, msg: "账号密码错误" });
    }
  } catch (err) {
    res.status(500).json({ code: 500, data: null, msg: "服务器错误" });
  }
});

// 获取所有用户
app.get("/api/users", authenticateToken, async (req, res) => {
  try {
    const [rows] = await pool.query("SELECT * FROM users");
    res.status(200).json({ code: 200, data: rows, msg: null });
  } catch (err) {
    console.error("获取用户错误", err);
    res
      .status(500)
      .json({ code: 500, data: null, msg: "Error fetching users" });
  }
});

// 创建新用户
app.post("/api/users", async (req, res) => {
  const { username, email, password, avatar } = req.body;

  try {
    await pool.query("INSERT INTO users SET ?", {
      username,
      email,
      password,
      avatar,
    });
    res.status(200).json({ code: 200, data: null, msg: "操作成功" });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, data: null, msg: "Error creating user" });
  }
});

// 配置静态文件服务
app.use("/uploads", express.static("uploads"));

// 运行服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
